import os
import random
import math

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class Weather(webapp.RequestHandler):
    def get(self):
        try:
            # Resquest must be in the form ...
            # http://droidguide.appspot.com/context/weather/read?latitude=<inteiro>&longitude=<inteiro>

            latitude = int(self.request.get('latitude'))
            longitude = int(self.request.get('longitude'))
            
            # Get weather information (TODO:)
            
            self.temperature = 0.0
            self.rain = 0.0
            self.humidity = 0.0
            
            self.response.headers['Content-Type'] = "text/xml"                        
            self.temperature = random.gauss(25,6)
            if self.temperature > 20:
                self.rain = random.gauss(10,30)
            else:
                self.rain = random.gauss(3,10)
                
            if self.rain < 5:
                self.humidity = random.gauss(3,0.1)
            elif self.rain > 5 and self.rain < 20:
                self.humidity =  random.gauss(0.4,0.1)
            elif self.rain > 20:
                self.humidity =  random.gauss(0.7,0.1)
            
            weather_values = {
                               'temperature' : self.temperature,
                               'rain' : math.floor(self.rain),
                               'humidity' : self.humidity}
            
            path = os.path.join(os.path.dirname(__file__), 'weather.xml')
            self.response.out.write(template.render(path, weather_values))
        except (typeError, ValueError): 
            # Wrong parameters passed           
            self.response.set_status(400, "Bad request")

application = webapp.WSGIApplication([('/context/weather/read', Weather)], debug=True)

def main():
    run_wsgi_app(application)
            
if __name__ == "__main__":
    main()
        
        